import java.util.concurrent.PriorityBlockingQueue;

public class RewritTimer {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务1：");
            }
        },1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务2：");
            }
        },2300);
    }
}
//我的定时器
class MyTimer{
    private Thread t=null;
    private PriorityBlockingQueue<MyTask> priorityBlockingQueue=new PriorityBlockingQueue<>();
    private Object locker=new Object();

    public MyTimer(){
        t=new Thread(){
            public void run(){
                while(true){
                    try{
                        System.out.println("this2"+this);
                        synchronized (locker){
                            MyTask myTask=priorityBlockingQueue.take();
                            long curTime=System.currentTimeMillis();
                            if(curTime< myTask.getTime()){
                                priorityBlockingQueue.put(myTask);//塞回去
                                locker.wait(myTask.getTime()-curTime);//等当前时间和定时器时间之差
                            }else {
                                myTask.run();
                            }
                        }
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();
    }
    //定时器中重要的方法schedule
    public void schedule(Runnable runnable,long after){
        MyTask task=new MyTask(runnable,System.currentTimeMillis()+after);
        priorityBlockingQueue.put(task);
        System.out.println("this1"+this);
        synchronized (locker){
            locker.notify();//唤醒等待中的线程
        }
    }
}
//定时器中的任务
class MyTask implements Comparable<MyTask>{
    //有两个参数，一个是线程任务，一个是时间
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable,Long time){
        this.time=time;
        this.runnable=runnable;
    }
    //得到定时器中任务的时间
    public long getTime(){
        return time;
    }
    //线程任务
    public void run(){
        runnable.run();
    }
    //比较器
    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time-o.time);
    }
}
